import sys
import requests

from mongo import MongoService


class Book(object):
    def __init__(self, book):
        self.book_path = book
        self.book = open(self.book_path, 'r')

    def word_list(self):
        word_list = set()

        word = ''
        for i in self.book.read():
            i = i.lower()
            if i >= 'a' and i <= 'z':
                word += i
            else:
                word_list.add(word)
                word = ''

        word_list = list(word_list)
        sorted(word_list)

        return word_list


class ShanBeiWord(object):
    def __init__(self, result, log):
        self.mongo = MongoService()
        self.result = open(result, 'w')
        self.log = open(log, 'w')

    def word_detail(self, word):
        get_data = {'word': word}
        res = requests.get('https://api.shanbay.com/bdc/search/',
                           params=get_data)
        self.result.write(f"{word}: {res.text}\n")

        log = ""
        res_json = res.json()
        if res_json['status_code'] == 0:
            self.mongo.save_word(res_json['data'])
        else:
            log = f"[ERROR] word {word} not save: {res.text}\n"

        log += f"[LOG] {word}: {res.status_code} - {res_json['msg']}"
        self.log.write(log + "\n")
        print(log)


if __name__ == '__main__':
    # usage:
    # python script book.txt result result.log
    book = Book(sys.argv[1])
    word_list = book.word_list()
    print(len(word_list))

    shanbei = ShanBeiWord(sys.argv[2], sys.argv[3])
    for word in word_list:
        if not word:
            continue
        shanbei.word_detail(word)
